package 网络编程.TCPFILEECHO3;


import 网络编程.TCPFileCopy1.StreamUtil;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-05
 * Time: 13:13
 */
public class TCPFILEEchoServer {
    /**
     * 1.编写一个客户端和服务端
     * 2.服务器端在8888端口监听
     * 3.客户端连接到服务端,发送一张图片
     * 4.服务器端接收到客户端发送的图片,保存到src下面,发送收到图片在退出
     * 5.客户端收到服务端发送的收到图片在退出
     * 6.程序要求使用StreamUtil.java
     */

    private ServerSocket serverSocket = null;

    public TCPFILEEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器正在监听8000端口...");
        Socket socket = serverSocket.accept();
        processService(socket);
    }

    public void processService(Socket socket) throws IOException {
        System.out.println("服务器接收到客户端连接...");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            //服务端这边接收客户端发来的图片
            BufferedInputStream bufferedInputStream = new
                    BufferedInputStream(inputStream);
            //将字节流转化成字节数组
            byte[] bytes = StreamUtil.streamByteArray(bufferedInputStream);

            //将图片保存到src路径中
            String destPath = "src//qie2.png";
            BufferedOutputStream bufferedOutputStream =
                    new BufferedOutputStream(new FileOutputStream(destPath));
            bufferedOutputStream.write(bytes);

            //服务器收到图片之后发送收到图片的信息给客户端
            BufferedWriter bufferedWriter = new BufferedWriter
                    (new OutputStreamWriter(outputStream));
            bufferedWriter.write("收到图片");
            bufferedWriter.flush();
            socket.shutdownOutput();//设置结束标记
            //关闭流
            bufferedWriter.close();
            bufferedInputStream.close();
            bufferedOutputStream.close();
        }finally {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPFILEEchoServer tcpfileEchoServer = new TCPFILEEchoServer(8000);
        tcpfileEchoServer.start();
    }
}
